package com.hb.trade.server.expert.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.expert.dto.*;
import com.hb.core.pojo.expert.entity.ExpertBase;
import com.hb.core.pojo.expert.entity.ExpertMajor;
import com.hb.core.pojo.expert.entity.ExpertUser;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.expert.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 专家库 前端控制器
 *
 * @author jinhaolin
 * @date 2022/1/18 14:04
 * @updater ljs
 * @updateDate 2022-2-11 11:07:48
 **/
@RestController
public class ExpertController {

    @Autowired
    private ExpertService expertService;

    @Autowired
    private ExpertMajorService expertMajorService;

    @Autowired
    private ExpertGroupService expertGroupService;

    @Autowired
    private ExpertUserService expertUserService;

    @Autowired
    private ExpertGroupMembersService expertGroupMembersService;

    /**
     * 抽取专家
     *
     * @param expertExtractParam
     * @return
     */
    @PostMapping("/expert/expertExtract")
    Message<List<ExpertDTO>> expertExtract(@RequestBody ExpertExtractParam expertExtractParam) {
        return expertService.expertExtract(expertExtractParam);
    }

    /**
     * 获取专业列表
     *
     * @param expertMajorDTO
     * @return
     */
    @ApiOperation(value = "根据父类code获取专业列表", notes = "获取专业列表，传入父级majorCode可以获取子级的列表;如果要获取第一级列表，父级majorCode为空值", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentCode", value = "父级专业code", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orgId", value = "所属企业id", dataTypeClass = Long.class),
    })
    @PostMapping("/expert/majorList")
    List<ExpertMajorDTO> majorList(@RequestBody ExpertMajorDTO expertMajorDTO) {
        List<ExpertMajorDTO> majorList = expertMajorService.majorList(expertMajorDTO);
        return majorList;
    }

    @ApiOperation(value = "获取全部专业列表", notes = "获取专业列表", httpMethod = "POST")
    @PostMapping("/expert/allMajorList")
    List<ExpertMajorDTO> allMajorList(@RequestBody ExpertMajorDTO expertMajorDTO) {
        QueryWrapper<ExpertMajor> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "parent_id", "parent_code", "major_code", "major_name");
        queryWrapper.orderByAsc("major_code");
        List<ExpertMajor> majorList = expertMajorService.list(queryWrapper);
        List<ExpertMajorDTO> expertMajorDTOList = new ArrayList<>();
        // 筛选一级专业
        for (ExpertMajor major : majorList) {
            if (major.getParentCode() == null) {
                ExpertMajorDTO majorDTO = major.to(ExpertMajorDTO.class);
                // 筛选二级专业
                for (ExpertMajor subMajor : majorList) {
                    if (subMajor.getParentCode() != null && subMajor.getParentCode().equals(majorDTO.getMajorCode())) {
                        SubExpertMajorDTO subExpertMajorDTO = subMajor.to(SubExpertMajorDTO.class);
                        // 筛选第三专业
                        for (ExpertMajor thirdMajor : majorList) {
                            if (thirdMajor.getParentCode() != null && thirdMajor.getParentCode().equals(subExpertMajorDTO.getMajorCode())) {
                                List<ExpertMajor> thirdMajorList = subExpertMajorDTO.getThirdMajorList();
                                if (thirdMajorList == null) {
                                    thirdMajorList = new ArrayList<>();
                                }
                                thirdMajorList.add(thirdMajor);
                                subExpertMajorDTO.setThirdMajorList(thirdMajorList);
                            }
                        }
                        List<SubExpertMajorDTO> subExpertMajorDTOList = majorDTO.getSubExpertMajorDTOList();
                        if (majorDTO.getSubExpertMajorDTOList() == null) {
                            subExpertMajorDTOList = new ArrayList<>();
                        }
                        subExpertMajorDTOList.add(subExpertMajorDTO);
                        majorDTO.setSubExpertMajorDTOList(subExpertMajorDTOList);
                    }
                }
                expertMajorDTOList.add(majorDTO);
            }
        }
        return expertMajorDTOList;
    }

    /**
     * 搜索专家
     *
     * @param expertDTO
     * @return
     */
    @ApiOperation(value = "搜索专家", notes = "搜索专家，只有一个参数，可以传专家姓名、手机号", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "searParam", value = "搜索参数", dataTypeClass = String.class),
    })
    @PostMapping("/expert/searchExpert")
    PageResult<ExpertDTO> expertSearch(@RequestBody ExpertDTO expertDTO) {
        return expertService.expertSearch(expertDTO);
    }

    /**
     * 返回全部专家
     *
     * @param expertDTO
     * @return
     */
    @ApiOperation(value = "返回全部专家", notes = "搜索专家，可以穿专业名称或者专家名称", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "searParam", value = "搜索参数", dataTypeClass = String.class),
    })
    @PostMapping("/expert/expertAll")
    public Message expertAll(@RequestBody ExpertDTO expertDTO) {
        List<ExpertDTO> expertDTOList = expertService.expertList(expertDTO);
        return expertDTOList.size() > 0 ? MsgUtil.success(expertDTOList) : MsgUtil.fail("暂无数据，导出失败");
    }

    /**
     * 保存专家，添加专家信息
     *
     * @param expertDTO
     * @return
     * @author: ljs
     * @date: 2022-2-10 11:20:01
     */
    @PostMapping("/expert/expertSave")
    public Message expertSave(@RequestBody ExpertDTO expertDTO) {
        if (expertDTO == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        String msg = expertDTO.paramsValid();
        if (StrUtil.isNotEmpty(msg)) {
            return MsgUtil.fail(msg);
        }

        // 验证专家手机号是否存在
        boolean b = expertService.countByPhoneNumberAndOrgId(expertDTO);
        if(!b){
            return MsgUtil.fail("此专家手机号已存在");
        }

        expertDTO.buildBaseData(1);
        Boolean result = expertService.save(expertDTO);
        return result ? MsgUtil.msg(MsgEnum.SUCCESS) : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 更新专家信息
     *
     * @param expertDTO
     * @return
     * @author: ljs
     * @date: 2022-2-10 11:20:01
     */
    @PostMapping("/expert/expertUpdate")
    public Message expertUpdate(@RequestBody ExpertDTO expertDTO) {
        if (expertDTO == null || expertDTO.getId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        // 验证专家手机号是否存在
        boolean b = expertService.countByPhoneNumberAndOrgId(expertDTO);
        if(!b){
            return MsgUtil.fail("此专家手机号已存在");
        }
        expertDTO.buildBaseData(2);
        Boolean result = expertService.updateById(expertDTO);
        return result ? MsgUtil.msg(MsgEnum.SUCCESS) : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 删除专家信息
     *
     * @param expertDTO
     * @return
     * @author: ljs
     * @date: 2022-2-10 11:20:01
     */
    @PostMapping("/expert/expertDelete")
    public Message expertDelete(@RequestBody ExpertDTO expertDTO) {
        if (expertDTO == null || expertDTO.getId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        expertDTO.setDeleteFlag(1);
        expertDTO.buildBaseData(2);
        Boolean result = expertService.updateById(expertDTO);
        return result ? MsgUtil.msg(MsgEnum.SUCCESS) : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 导入专家信息
     *
     * @param expertDTOList
     * @return
     * @author: ljs
     * @date: 2022-2-10 11:20:01
     */
    @PostMapping("/expert/expertImport")
    public Message expertImport(@RequestBody List<ExpertDTO> expertDTOList) {
        if (null == expertDTOList) {
            return MsgUtil.fail("专家信息不能为空！");
        }
        List<ExpertBase> expertBaseList = new ArrayList<>();
        for (ExpertDTO expertDTO : expertDTOList) {
            // 将专业名转换为专业编码
            LambdaQueryWrapper<ExpertMajor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(ExpertMajor::getMajorName, expertDTO.getMajorName());
            queryWrapper.last("limit 1");
            ExpertMajor expertMajor = expertMajorService.getOne(queryWrapper);
            // 判断专业是否存在
            if (expertMajor == null) {
                return MsgUtil.fail(expertDTO.getMajorName() + "专业不存在，请输入正确专业名称");
            }

            //根据身份证验证该用户是否存在
            LambdaQueryWrapper<ExpertBase> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(ExpertBase::getId);
            lambdaQueryWrapper.eq(ExpertBase::getPhoneNumber, expertDTO.getPhoneNumber());
            lambdaQueryWrapper.eq(ExpertBase::getOrgId, expertDTO.getOrgId());
            lambdaQueryWrapper.eq(ExpertBase::getMajorCode, expertMajor.getMajorCode());
            lambdaQueryWrapper.eq(ExpertBase::getDeleteFlag, 0);
            lambdaQueryWrapper.last("limit 1");
            ExpertBase member = expertService.getOne(lambdaQueryWrapper);
            if (member != null) {
                return MsgUtil.fail(expertDTO.getPhoneNumber() + "手机号已存在");
            }

            expertDTO.buildBaseData(1);

            if (expertDTO.getSexStr().contains("男")) {
                expertDTO.setSex(0);
            } else if (expertDTO.getSexStr().contains("女")) {
                expertDTO.setSex(1);
            }
            ExpertBase expertBase = expertDTO.to(ExpertBase.class);
            expertBase.setMajorCode(expertMajor.getMajorCode());
            expertBaseList.add(expertBase);
        }
        Boolean result = expertService.saveBatch(expertBaseList);
        return result ? MsgUtil.success("专家导入成功") : MsgUtil.fail("专家导入失败！");
    }

    /**
     * 保存专家组信息
     *
     * @param expertGroupDTO
     * @return
     */
    @PostMapping("/expert/expertGroupSave")
    public Message expertGroupSave(@RequestBody ExpertGroupDTO expertGroupDTO) {
        if (expertGroupDTO == null || expertGroupDTO.getExpertList() == null || expertGroupDTO.getCreateId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        // 查询抽取项目是否已存在
        boolean b = expertGroupService.countByProjectNameAndOrgId(expertGroupDTO);
        if(!b){
            return MsgUtil.fail("当前招标项目已抽取专家，请更换招标项目名称");
        }

        boolean result = expertGroupService.expertGroupSave(expertGroupDTO);
        return result ? MsgUtil.msg(MsgEnum.SUCCESS) : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 查询专家组
     *
     * @param expertGroupDTO
     * @return
     */
    @PostMapping("/expert/expertGroupList")
    public Message expertGroupList(@RequestBody ExpertGroupDTO expertGroupDTO) {
        if (expertGroupDTO == null || expertGroupDTO.getUserId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        PageResult<ExpertGroupDTO> expertGroupList = expertGroupService.listExpertGroup(expertGroupDTO);
        return MsgUtil.success(expertGroupList);
    }

    /**
     * 查询专家组详情
     *
     * @param expertGroupDTO
     * @return
     */
    @PostMapping("/expert/expertGroupDetail")
    public Message<ExpertGroupDTO> luoyexpertGroupDetail(@RequestBody ExpertGroupDTO expertGroupDTO) {
        if (expertGroupDTO == null || expertGroupDTO.getId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        ExpertGroupDTO groupDTO = expertGroupService.expertGroupDetail(expertGroupDTO);
        return MsgUtil.success(groupDTO);

    }

    /**
     * 删除专家组
     *
     * @param expertGroupDTO
     * @return
     */
    @PostMapping("/expert/expertGroupDelete")
    public Message expertGroupDelete(@RequestBody ExpertGroupDTO expertGroupDTO) {
        if (expertGroupDTO == null || expertGroupDTO.getId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        boolean result = expertGroupService.removeExpertGroup(expertGroupDTO);
        return result ? MsgUtil.msg(MsgEnum.SUCCESS) : MsgUtil.fail(MsgEnum.FAILURE.msg());

    }


    /**
     * 查询专家系统账号信息
     *
     * @param expertUser
     * @return
     */
    @PostMapping("/expert/getExpertUser")
    public Message<ExpertUser> getExpertUser(@RequestBody ExpertUser expertUser) {
        if (expertUser == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        if (StrUtil.isEmpty(expertUser.getUsername())) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        if (StrUtil.isEmpty(expertUser.getPassword())) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }

        LambdaQueryWrapper<ExpertUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExpertUser::getUsername, expertUser.getUsername());
        queryWrapper.eq(ExpertUser::getPassword, expertUser.getPassword());
        if (null != expertUser.getOrgId()) {
            queryWrapper.eq(ExpertUser::getOrgId, expertUser.getOrgId());
        }
        queryWrapper.last("limit 1");
        ExpertUser user = expertUserService.getOne(queryWrapper);
        if (user == null) {
            return MsgUtil.fail("账号密码错误！该账号不存在");
        } else {
            return MsgUtil.success(user);
        }
    }

    /**
     * 新增一个专家系统账号信息
     *
     * @param expertUser
     * @return
     */
    @PostMapping("/expert/expertUserSave")
    public Message<Boolean> expertUserSave(@RequestBody ExpertUser expertUser) {
        boolean result = expertUserService.save(expertUser);
        return result ? MsgUtil.success() : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 删除一个专家系统账号信息
     *
     * @param expertUser
     * @return
     */
    @PostMapping("/expert/expertUserDelete")
    public Message<Boolean> expertUserDelete(@RequestBody ExpertUser expertUser) {
        if (expertUser == null || expertUser.getId() == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        boolean result = expertUserService.removeById(expertUser.getId());
        return result ? MsgUtil.success() : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 修改专家抽取系统账号信息
     *
     * @param expertUser
     * @return
     */
    @PostMapping("/expert/expertUserUpdate")
    public Message<Boolean> expertUserUpdate(@RequestBody ExpertUser expertUser) {
        if (expertUser == null || expertUser.getId() == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM_TYPE.msg());
        }
        boolean result = expertUserService.updateById(expertUser);
        return result ? MsgUtil.success() : MsgUtil.fail(MsgEnum.FAILURE.msg());
    }

    /**
     * 根据用户名查询该用户的信息
     *
     * @param userName
     * @return
     */
    @PostMapping("/expert/expertUserSearchByUserName")
    public Message<ExpertUser> expertUserSearchByUserName(@RequestBody String userName) {
        if (userName == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM_TYPE.msg());
        }
        // 查询用户
        LambdaQueryWrapper<ExpertUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExpertUser::getUsername, userName);
        queryWrapper.last("limit 1");
        ExpertUser user = expertUserService.getOne(queryWrapper);
        return MsgUtil.success(user);
    }


    /**
     * 查询抽取专家的记录
     *
     * @param expertGroupMembersDTO
     * @return org.fzzn.core.model.msg.Message<java.util.List < com.hb.core.pojo.expert.dto.ExpertGroupMembersDTO>>
     * @author tian
     * @date 2022-4-14 15:57
     */
    @PostMapping("/expert/selectExpertGroupMembersByGroupId")
    public Message<List<ExpertGroupMembersDTO>> selectExpertGroupMembersByGroupId(@RequestBody ExpertGroupMembersDTO expertGroupMembersDTO) {
        return expertGroupMembersService.selectExpertGroupMembersByGroupId(expertGroupMembersDTO);
    }


    /**
     * 补充抽取专家
     *
     * @param expertGroupMembersDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.ExpertDTO>
     * @author tian
     * @date 2022-4-14 16:08
     */
    @PostMapping("/expert/supplementExtract")
    public Message<String> supplementExtract(@RequestBody ExpertGroupMembersDTO expertGroupMembersDTO) {
        return expertGroupMembersService.supplementExtract(expertGroupMembersDTO);
    }

    /**
     * 判断指定企业是否拥有私有专家帐号
     *
     * @param orgId 企业ID
     * @return
     * @author zhaojk
     */
    @PostMapping("/expert/existsByOrgId")
    public Message<Boolean> existsByOrgId(Long orgId) {
        if (orgId == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        QueryWrapper<ExpertUser> wrapper = ExpertUser.wrapper();
        wrapper.eq("org_id", orgId);
        long count = expertUserService.count(wrapper);
        return MsgUtil.success(count > 0);
    }

    /**
     * 判断指定企业是否拥有私有专家帐号
     *
     * @param orgId 企业ID
     * @return
     * @author zhaojk
     */
    @PostMapping("/expert/getByOrgId")
    public Message<ExpertUser> getByOrgId(Long orgId) {
        if (orgId == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        QueryWrapper<ExpertUser> wrapper = ExpertUser.wrapper();
        wrapper.eq("org_id", orgId).last("limit 1");
        ExpertUser one = expertUserService.getOne(wrapper);
        if (one == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(one);
    }
}
